<template>
	<view>
		<!-- 地址 -->
		<navigator url="/pages/address/address?source=1" v-show="isAddress" class="address-section">
			<view class="order-content" >
				<text class="yticon icon-shouhuodizhi"></text>
				<view class="cen">
					<view class="top">
						<text class="name">{{addressData.name}}</text>
						<text class="mobile">{{addressData.mobile}}</text>
					</view>
					<text class="address">{{addressData.address}}</text>
				</view>
				<text class="yticon icon-you"></text>
			</view>

			<image class="a-bg" src=""></image>
		</navigator>
		
		<navigator url="/pages/address/address?source=1" v-show="!isAddress" class="address-section">
			<view class="order-content" >
				<text class="yticon icon-shouhuodizhi"></text>
				<view class="cen">
					<view class="top">
						<text class="name">请选择收货地址</text>
					</view>
				</view>
				<text class="yticon icon-you"></text>
			</view>
		
			<image class="a-bg" src=""></image>
		</navigator>

		<view class="goods-section" v-show="isD">
			<view class="g-header b-b">
				<image class="logo" src="http://duoduo.qibukj.cn/./Upload/Images/20190321/201903211727515.png"></image>
				<text class="name">{{goodsDetails[0].brandName}}</text>
			</view>
			<!-- 商品列表 -->
			<view class="g-item">
				<image :src="goodsDetails[0].picUrl"></image>
				<view class="right">
					<text class="title clamp">{{goodsDetails[0].goodsName}}</text>
					<text class="spec">{{goodsDetails[0].specifications}}</text>
					<view class="price-box">
						<text class="price">￥{{goodsDetails[0].price}}</text>
						<text class="number">x {{goodsDetails[0].number}}</text>
					</view>
				</view>
			</view>
		</view>
		
		<view class="goods-section" v-show="isEditing"
				v-for="(brand, brandIndex) in orderData.brands" :key="brandIndex">
			<view class="g-header b-b">
				<image class="logo" src="http://duoduo.qibukj.cn/./Upload/Images/20190321/201903211727515.png"></image>
				<text class="name">{{brand.name}}</text>
			</view>
			<!-- 商品列表 -->
			<view class="g-item" v-for="(goods, goodsIndex) in brand.goods" :key="goodsIndex">
				<image :src="goods.picUrl"></image>
				<view class="right">
					<text class="title clamp">{{goods.goodsName}}</text>
					<text class="spec">{{goods.specifications}}</text>
					<view class="price-box">
						<text class="price">￥{{goods.price}}</text>
						<text class="number">x {{goods.number}}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 优惠明细 -->
		<view class="yt-list" v-if="!isMai && !isMiao">
			<view class="yt-list-cell b-b" @click="goToCouponPage">
				<view class="cell-icon">
					券
				</view>
				<text class="cell-tit clamp">优惠券</text>
				<text class="cell-tip active">
					{{ selectedCoupon ? `已选¥${selectedCoupon.discount}` : '选择优惠券' }}
				  </text>
				<text class="cell-more wanjia wanjia-gengduo-d"></text>
			</view>
			<view class="yt-list-cell b-b">
				<view class="cell-icon hb">
					减
				</view>
				<text class="cell-tit clamp">商家促销</text>
				<text class="cell-tip disabled">暂无可用优惠</text>
			</view>
		</view>
		<!-- 金额明细 -->
		<view class="yt-list">
			<view class="yt-list-cell b-b">
				<text class="cell-tit clamp">商品金额</text>
				<text class="cell-tip">￥{{sumPrice}}</text>
			</view>
			<view class="yt-list-cell b-b">
				<text class="cell-tit clamp">优惠金额</text>
				<text class="cell-tip red">-￥{{preferential}}</text>
			</view>
			<view class="yt-list-cell b-b">
				<text class="cell-tit clamp">运费</text>
				<text class="cell-tip">{{freight}}</text>
			</view>
			<view class="yt-list-cell desc-cell">
				<text class="cell-tit clamp">备注</text>
				<input class="desc" type="text" v-model="desc" placeholder="请填写备注信息" placeholder-class="placeholder" />
			</view>
		</view>
		
		<!-- 底部 -->
		<view class="footer">
			<view class="price-content">
				<text>实付款</text>
				<text class="price-tip">￥</text>
				<text class="price">{{actuaPayment}}</text>
			</view>
			<text class="submit" @click="submit">提交订单</text>
		</view>
		
		<!-- 优惠券面板 -->
		<view class="mask" :class="maskState===0 ? 'none' : maskState===1 ? 'show' : ''" @click="toggleMask">
			<view class="mask-content" @click.stop.prevent="stopPrevent">
				<!-- 优惠券页面，仿mt -->
				<view class="coupon-item" v-for="(item,index) in couponList" :key="index">
					<view class="con">
						<view class="left">
							<text class="title">{{item.title}}</text>
							<text class="time">有效期至2019-06-30</text>
						</view>
						<view class="right">
							<text class="price">{{item.price}}</text>
							<text>满30可用</text>
						</view>
						
						<view class="circle l"></view>
						<view class="circle r"></view>
					</view>
					<text class="tips">限新用户使用</text>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {getAddressDefault} from '@/config/api/address.js';
	import {
		getCouponList,
	} from '@/config/api/coupon.js';
	import { mapState } from 'vuex'; 
	export default {
		data() {
			return {
				maskState: 0, //优惠券面板显示状态
				desc: '', //备注
				payType: 1, //1微信 2支付宝
				goodsDetails: [],
				// 商品总金额
				sumPrice: 0,
				isAddress: false,
				// 优惠金额
				preferential: 0,
				// 运费
				freight: 0,
				// 实际需要付款
				actuaPayment: 0,
				isD: false,
				isEditing: false,
				
				addressData: {
					
				},
				orderData: {
					brands: [],  // 品牌分组数据
					total: 0     // 总金额
				},
				selectedCoupon: null,
				couponList : [],
				isMiao : false,
				isMai : false
			}
		},
		computed: {
			...mapState(['userInfo']), // 添加userInfo映射
			// 优惠金额计算
			 preferential() {
			    return this.selectedCoupon ? 
			      parseFloat(this.selectedCoupon.discount) : 0;
			  },
			  
			  // 实付款计算
			  actuaPayment() {
			    const sum = parseFloat(this.sumPrice) || 0;
			    const freight = parseFloat(this.freight) || 0;
			    const discount = this.preferential;
			    return (sum + freight - discount).toFixed(2);
			  }
		},
		onLoad(options) {
			this.initData(options);
			// 在onLoad中注册事件监听
			uni.$on('couponSelected', this.onCouponSelected);
			this.loadDefaultCoupon();
		},
		 onUnload() {
		    // 页面卸载时移除事件监听
		    uni.$off('couponSelected', this.onCouponSelected);
		  },
		onShow() {
		   // 确保正确监听优惠券选择事件
		    uni.$on('couponSelected', this.onCouponSelected);
		},
		onHide() {
		    // 页面隐藏时移除监听
		    uni.$off('couponSelected', this.onCouponSelected);
		},
		watch: {
		  selectedCoupon(newVal) {
		    this.preferential = newVal ? parseFloat(newVal.discount) : 0;
		    this.updatePayment();
		  },
		  sumPrice() {
		    this.updatePayment();
		  }
		},
		methods: {
			
			async initData(options) {
				try {
					// 解析URL参数
					const dataStr = decodeURIComponent(options.data || "{}");
					const orderData = JSON.parse(dataStr);
					this.sumPrice = orderData.total;
					
					// this.freight = 0; 
					// this.selectedCoupon = null;
					// 将价格和运费转换为分（整数）进行计算
					let sumPriceInFen = this.sumPrice * 100;
					let freightInFen = this.freight * 100;
					let preferentialInFen = this.preferential * 100;
					let actualPaymentInFen = (sumPriceInFen + freightInFen - preferentialInFen);
					// 再转换回元
					this.actuaPayment = actualPaymentInFen / 100; 
					
					this.isMiao = orderData.isMiao;
					this.isMai = orderData.isMai;
					// 验证数据结构
					if (orderData.brands && Array.isArray(orderData.brands)) {
						this.orderData = {
							brands: orderData.brands.map(brand => ({
								name: brand.name,
								goods: brand.goods.map(goods => ({
									...goods,
									price: Number(goods.price).toFixed(2),
								}))
							})),
							total: Number(orderData.total).toFixed(2)
							
						};
						console.log("订单" + orderData);
						this.loadDefaultCoupon();
						console.log(JSON.stringify(orderData.brands[0].goods[0].userId, null, 2));
						this.isEditing = true
						
						try {
							const res = await getAddressDefault({userId: orderData.brands[0].goods[0].userId})
							if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code === 200) {
								this.addressData = res.data.data;
								console.log(this.addressData);
								if (this.addressData && this.addressData.address && this.addressData.address.trim()!== '') {
									this.isAddress = true;
								}
							} else {
								console.error('暂无默认地址:', res?.data?.msg || '未知错误');
							}
						} catch (error) {
							console.error('接口异常:', error)
							this.$message.error('数据加载失败')
						}
						
						
					} else {
						throw new Error("数据格式错误");
					}
				} catch (e) {
					console.error("数据解析失败:", e);
					uni.showToast({ title: "订单数据异常", icon: "none" });
					setTimeout(() => uni.navigateBack(), 1500);
				}
			},
			// 更新支付金额
			  updatePayment() {
			    this.preferential = this.selectedCoupon ? parseFloat(this.selectedCoupon.discount) : 0;
			    this.actuaPayment = (this.sumPrice + this.freight - this.preferential).toFixed(2);
			  },
			 async loadDefaultCoupon() {
				 if (this.isMiao && this.isMai){
					 return;
				 }
				 
			    try {
			      const userId = this.userInfo.id;
			      const res = await getCouponList({ userId, status: 0 });
			      
			      if (res.data.code === 200 && res.data.data.length > 0) {
			        // 过滤可用优惠券并排序（折扣从高到低）
			        const availableCoupons = res.data.data
			          .filter(coupon => this.sumPrice >= coupon.min)
			          .sort((a, b) => b.discount - a.discount);
			          
			        if (availableCoupons.length > 0) {
			          // 默认选中最优优惠券
			          this.selectedCoupon = availableCoupons[0];
			          console.log('默认选中优惠券:', this.selectedCoupon);
			        }
			      }
			    } catch (error) {
			      console.error('加载默认优惠券失败:', error);
			    }
			  },
			
			// 跳转到优惠券页面
			// goToCouponPage() {
			//   // 传递当前选中的优惠券
			//   const selected = this.selectedCoupon ? encodeURIComponent(JSON.stringify(this.selectedCoupon)) : '';
			//   const goodsList = this.orderData.brands.flatMap(brand => 
			//       brand.goods.map(g => ({
			//         id: g.goodsId,
			//         categoryId: g.categoryId, // 确保商品对象包含类目ID
			//         price: g.price
			//       }))
			//     );
			// 	const params = new URLSearchParams({
			// 	    sumPrice: this.sumPrice,
			// 	    selectedCoupon: this.selectedCoupon ? JSON.stringify(this.selectedCoupon) : '',
			// 	    goodsList: JSON.stringify(goodsList)
			// 	  }).toString();
			//   console.log("goodslist:"+this.orderData);
			//   console.log(JSON.stringify(this.orderData, null, 2));
			//   console.log(JSON.stringify(goodsList, null, 2));
			//  //  const params = {
			// 	//   sumPrice: this.sumPrice,
			// 	//   selectedCoupon: this.selectedCoupon ? encodeURIComponent(JSON.stringify(this.selectedCoupon)) : '',
			// 	//   goodsList: encodeURIComponent(JSON.stringify(goodsList))
			// 	// };
			// //const url = `/pages/user/coupon?sumPrice=${params.sumPrice}&selectedCoupon=${params.selectedCoupon}&goodsList=${params.goodsList}`;
			// 	const url = `/pages/user/coupon?${params}`;
			//   // uni.navigateTo({
			//   //   url: `/pages/user/coupon?sumPrice=${this.sumPrice}&selectedCoupon=${selected}`
			//   // });
			//   console.log("跳转URL:", url);
			//     uni.navigateTo({ url });
			// },
			goToCouponPage() {
			  const goodsList = this.orderData.brands.flatMap(brand => 
			    brand.goods.map(g => ({
			      id: g.goodsId,
			      categoryId: g.categoryId,
			      price: g.price
			    }))
			  );
			  
			  // 构建查询参数
			  const params = {
			    sumPrice: this.sumPrice,
			    selectedCoupon: this.selectedCoupon ? JSON.stringify(this.selectedCoupon) : '',
			    goodsList: JSON.stringify(goodsList)
			  };
			  
			  // 手动构建查询字符串
			  const queryString = Object.keys(params)
			    .map(key => {
			      if (params[key] !== undefined && params[key] !== null && params[key] !== '') {
			        return `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`;
			      }
			      return '';
			    })
			    .filter(Boolean)
			    .join('&');
			  
			  const url = `/pages/user/coupon?${queryString}`;
			  
			  console.log("跳转URL:", url);
			  uni.navigateTo({ url });
			},
		 // 完善优惠券选择处理方法
			 onCouponSelected(coupon) {
			   console.log('收到优惠券:', coupon);
			   this.selectedCoupon = coupon; 
			   
			   // 添加调试日志
			   console.log('优惠券折扣:', coupon.discount);
			   console.log('计算前金额:', this.sumPrice);
			   // this.preferential = coupon.discount;
			   // this.actuaPayment = this.sumPrice + this.freight - this.preferential;
			   this.updatePayment();
			   console.log('优惠金额:', this.preferential);
			   console.log('实付款:', this.actuaPayment);
			   
			    this.$forceUpdate();
			   
			   uni.showToast({
				 title: `已选择¥${coupon.discount}优惠券`,
				 icon: 'success'
			   });
			 },
			
			 
			//显示优惠券面板
			// toggleMask(type){
			// 	let timer = type === 'show' ? 10 : 300;
			// 	let	state = type === 'show' ? 1 : 0;
			// 	this.maskState = 2;
			// 	setTimeout(()=>{
			// 		this.maskState = state;
			// 	}, timer)
			// },
			numberChange(data) {
				this.number = data.number;
			},
			changePayType(type){
				this.payType = type;
			},
			submit(){
				 if (!this.addressData || !this.addressData.address || this.addressData.address.trim() === '') {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none',
						duration: 2000
					});
					return; // 阻止继续执行跳转
				}
				const orderParams = {
				    orderData: this.orderData,
				    addressData: this.addressData,
				    sumPrice: this.sumPrice,
				    preferential: this.preferential,
				    freight: this.freight,
				    actuaPayment: this.actuaPayment,
					selectedCoupon : this.selectedCoupon,
					message : this.desc,
				  };
				  const paramsStr = encodeURIComponent(JSON.stringify(orderParams));
				uni.navigateTo({
					url: `/pages/money/pay?params=${paramsStr}`
				})
			},
			stopPrevent(){}
		}
	}
</script>

<style lang="scss">
	page {
		background: $page-color-base;
		padding-bottom: 100upx;
	}

	.address-section {
		padding: 30upx 0;
		background: #fff;
		position: relative;

		.order-content {
			display: flex;
			align-items: center;
		}

		.icon-shouhuodizhi {
			flex-shrink: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 90upx;
			color: #888;
			font-size: 44upx;
		}

		.cen {
			display: flex;
			flex-direction: column;
			flex: 1;
			font-size: 28upx;
			color: $font-color-dark;
		}

		.name {
			font-size: 34upx;
			margin-right: 24upx;
		}

		.address {
			margin-top: 16upx;
			margin-right: 20upx;
			color: $font-color-light;
		}

		.icon-you {
			font-size: 32upx;
			color: $font-color-light;
			margin-right: 30upx;
		}

		.a-bg {
			position: absolute;
			left: 0;
			bottom: 0;
			display: block;
			width: 100%;
			height: 5upx;
		}
	}

	.goods-section {
		margin-top: 16upx;
		background: #fff;
		padding-bottom: 1px;

		.g-header {
			display: flex;
			align-items: center;
			height: 84upx;
			padding: 0 30upx;
			position: relative;
		}

		.logo {
			display: block;
			width: 50upx;
			height: 50upx;
			border-radius: 100px;
		}

		.name {
			font-size: 30upx;
			color: $font-color-base;
			margin-left: 24upx;
		}

		.g-item {
			display: flex;
			margin: 20upx 30upx;

			image {
				flex-shrink: 0;
				display: block;
				width: 140upx;
				height: 140upx;
				border-radius: 4upx;
			}

			.right {
				flex: 1;
				padding-left: 24upx;
				overflow: hidden;
			}

			.title {
				font-size: 30upx;
				color: $font-color-dark;
			}

			.spec {
				font-size: 26upx;
				color: $font-color-light;
			}

			.price-box {
				display: flex;
				align-items: center;
				font-size: 32upx;
				color: $font-color-dark;
				padding-top: 10upx;

				.price {
					margin-bottom: 4upx;
				}
				.number{
					font-size: 26upx;
					color: $font-color-base;
					margin-left: 20upx;
				}
			}

			.step-box {
				position: relative;
			}
		}
	}
	.yt-list {
		margin-top: 16upx;
		background: #fff;
	}

	.yt-list-cell {
		display: flex;
		align-items: center;
		padding: 10upx 30upx 10upx 40upx;
		line-height: 70upx;
		position: relative;

		&.cell-hover {
			background: #fafafa;
		}

		&.b-b:after {
			left: 30upx;
		}

		.cell-icon {
			height: 32upx;
			width: 32upx;
			font-size: 22upx;
			color: #fff;
			text-align: center;
			line-height: 32upx;
			background: #f85e52;
			border-radius: 4upx;
			margin-right: 12upx;

			&.hb {
				background: #ffaa0e;
			}

			&.lpk {
				background: #3ab54a;
			}

		}

		.cell-more {
			align-self: center;
			font-size: 24upx;
			color: $font-color-light;
			margin-left: 8upx;
			margin-right: -10upx;
		}

		.cell-tit {
			flex: 1;
			font-size: 26upx;
			color: $font-color-light;
			margin-right: 10upx;
		}

		.cell-tip {
			font-size: 26upx;
			color: $font-color-dark;

			&.disabled {
				color: $font-color-light;
			}

			&.active {
				color: $base-color;
			}
			&.red{
				color: $base-color;
			}
		}

		&.desc-cell {
			.cell-tit {
				max-width: 90upx;
			}
		}

		.desc {
			flex: 1;
			font-size: $font-base;
			color: $font-color-dark;
		}
	}
	
	/* 支付列表 */
	.pay-list{
		padding-left: 40upx;
		margin-top: 16upx;
		background: #fff;
		.pay-item{
			display: flex;
			align-items: center;
			padding-right: 20upx;
			line-height: 1;
			height: 110upx;	
			position: relative;
		}
		.icon-weixinzhifu{
			width: 80upx;
			font-size: 40upx;
			color: #6BCC03;
		}
		.icon-alipay{
			width: 80upx;
			font-size: 40upx;
			color: #06B4FD;
		}
		.icon-xuanzhong2{
			display: flex;
			align-items: center;
			justify-content: center;
			width: 60upx;
			height: 60upx;
			font-size: 40upx;
			color: $base-color;
		}
		.tit{
			font-size: 32upx;
			color: $font-color-dark;
			flex: 1;
		}
	}
	
	.footer{
		position: fixed;
		left: 0;
		bottom: 0;
		z-index: 995;
		display: flex;
		align-items: center;
		width: 100%;
		height: 90upx;
		justify-content: space-between;
		font-size: 30upx;
		background-color: #fff;
		z-index: 998;
		color: $font-color-base;
		box-shadow: 0 -1px 5px rgba(0,0,0,.1);
		.price-content{
			padding-left: 30upx;
		}
		.price-tip{
			color: $base-color;
			margin-left: 8upx;
		}
		.price{
			font-size: 36upx;
			color: $base-color;
		}
		.submit{
			display:flex;
			align-items:center;
			justify-content: center;
			width: 280upx;
			height: 100%;
			color: #fff;
			font-size: 32upx;
			background-color: $base-color;
		}
	}
	
	/* 优惠券面板 */
	.mask{
		display: flex;
		align-items: flex-end;
		position: fixed;
		left: 0;
		top: var(--window-top);
		bottom: 0;
		width: 100%;
		background: rgba(0,0,0,0);
		z-index: 9995;
		transition: .3s;
		
		.mask-content{
			width: 100%;
			min-height: 30vh;
			max-height: 70vh;
			background: #f3f3f3;
			transform: translateY(100%);
			transition: .3s;
			overflow-y:scroll;
		}
		&.none{
			display: none;
		}
		&.show{
			background: rgba(0,0,0,.4);
			
			.mask-content{
				transform: translateY(0);
			}
		}
	}

	/* 优惠券列表 */
	.coupon-item{
		display: flex;
		flex-direction: column;
		margin: 20upx 24upx;
		background: #fff;
		.con{
			display: flex;
			align-items: center;
			position: relative;
			height: 120upx;
			padding: 0 30upx;
			&:after{
				position: absolute;
				left: 0;
				bottom: 0;
				content: '';
				width: 100%;
				height: 0;
				border-bottom: 1px dashed #f3f3f3;
				transform: scaleY(50%);
			}
		}
		.left{
			display: flex;
			flex-direction: column;
			justify-content: center;
			flex: 1;
			overflow: hidden;
			height: 100upx;
		}
		.title{
			font-size: 32upx;
			color: $font-color-dark;
			margin-bottom: 10upx;
		}
		.time{
			font-size: 24upx;
			color: $font-color-light;
		}
		.right{
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			font-size: 26upx;
			color: $font-color-base;
			height: 100upx;
		}
		.price{
			font-size: 44upx;
			color: $base-color;
			&:before{
				content: '￥';
				font-size: 34upx;
			}
		}
		.tips{
			font-size: 24upx;
			color: $font-color-light;
			line-height: 60upx;
			padding-left: 30upx;
		}
		.circle{
			position: absolute;
			left: -6upx;
			bottom: -10upx;
			z-index: 10;
			width: 20upx;
			height: 20upx;
			background: #f3f3f3;
			border-radius: 100px;
			&.r{
				left: auto;
				right: -6upx;
			}
		}
	}

</style>
